package com.edu.app.schedule;

import cn.jpush.api.push.model.PushPayload;
import com.edu.app.bean.core.SysActivity;
import com.edu.app.bean.core.SysUser;
import com.edu.app.bean.linkbeans.SysUserActivity;
import com.edu.app.bean.virtualbean.UserActWx;
import com.edu.app.model.wechat.WxErrorException;
import com.edu.app.model.wechat.msg.WechatTemplateMsg;
import com.edu.app.service.sys.core.SysActivityService;
import com.edu.app.service.sys.core.SysUserService;
import com.edu.app.service.sys.linkservices.SysUserActivityService;
import com.edu.app.service.sys.wechat.WechatTemplateMsgService;
import com.edu.app.threadlocal.TenantContext;
import com.edu.app.util.CommonUtils;
import com.edu.app.util.json.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.TreeMap;

import static cn.jpush.api.push.model.notification.PlatformNotification.ALERT;

@Component
public class ScheduledTasks {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysActivityService sysActivityService;

    @Autowired
    private SysUserActivityService sysUserActivityService;

    @Autowired
    private WechatTemplateMsgService wechatTemplateMsgService;

    @Scheduled(cron="0 0/2 * * * ?")
    public void sendWxNotifications(){
        //Step0, disable the tenant cause we will loop all users
        TenantContext.setNeedTenantId(Boolean.FALSE);

        //Step1, get the user list who has the corresponding openId
        List<UserActWx> userActWxList = sysUserActivityService.getUserActWx();

        //Step2, Loop the user and send msgs
        for(UserActWx userActWx: userActWxList){
            //get the lesson activities within 15 minutes
            TreeMap<String,TreeMap<String,String>> params = new TreeMap<String,TreeMap<String,String>>();
            //根据具体模板参数组装
            params.put("first", WechatTemplateMsg.item(userActWx.getCustomer() + "小朋友的课程将在15分钟后开始", "#1296db"));
            params.put("keyword1", WechatTemplateMsg.item(userActWx.getLesson(), "#000000"));
            params.put("keyword2", WechatTemplateMsg.item(CommonUtils.dateToString(userActWx.getTime()), "#000000"));
            params.put("keyword3", WechatTemplateMsg.item(userActWx.getCompany(), "#000000"));
            params.put("remark", WechatTemplateMsg.item(userActWx.getNickname() + "老师请提前做好备课工作", "#1296db"));

            WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
            wechatTemplateMsg.setTemplate_id("EHOzB7rGr2sjL5keh9SJdzMwzqtr95mRsDTuQuQ44F8");
            wechatTemplateMsg.setTouser(userActWx.getWx_open_id());
            wechatTemplateMsg.setData(params);
            wechatTemplateMsg.setUrl("http://www.edumavin.com/mavinTeacher/#/lesson");
            String data = null;
            try {
                data = JsonUtil.toJson(wechatTemplateMsg);
                wechatTemplateMsgService.sendTemplate(data);
                SysActivity sysActivity = sysActivityService.getObjectById(userActWx.getId());
                sysActivity.setWx_flag(true);
                sysActivityService.update(sysActivity);
            }catch(JsonProcessingException e){

            }catch(WxErrorException e)
            {

            }
        }

        //Last, enable the tenant id check
        TenantContext.setNeedTenantId(Boolean.TRUE);
    }

    @Scheduled(cron="0 0/2 * * * ?")
    public void sendAppNotifications(){
        /*JPushClient jpushClient = new JPushClient("1b09cdf5e5c367f15f95c60c", "10e514b3fad8697ae1912d0c", null, ClientConfig.getInstance());

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_all_alert();

        try {
            PushResult result = jpushClient.sendPush(payload);
            //LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            //LOG.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            //LOG.error("Should review the error, and fix the request", e);
            //LOG.info("HTTP Status: " + e.getStatus());
            //LOG.info("Error Code: " + e.getErrorCode());
            //LOG.info("Error Message: " + e.getErrorMessage());
        }*/
    }

    public static PushPayload buildPushObject_all_all_alert() {
        return PushPayload.alertAll(ALERT);
    }
}
